package com.zhw.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * @author weizhang52
 * @description: HelloNetty服务器：客户端请求，服务端返回
 * @date 2019/4/16
 * @modify
 */
@Slf4j
public class HelloNettyServer {

    public static void main(String[] args) {

        // 主线程组，接收连接
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        // 从线程组，处理主线程组分发的任务
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        // 启动类，Netty服务器创建：设置主从线程组，设置NIO的双向通道；子处理器，用于处理workerGroup
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new HelloNettyInit());
            // 启动Server，监听端口，启动方式为同步
            // 绑定端口，同步等待成功
            ChannelFuture channelFuture = serverBootstrap.bind(17777).sync();
            log.info("[HelloNettyServer] Netty服务端已启动");

            // 监听关闭的channel，设置为同步方式
            // 等待服务端监听端口关闭
            channelFuture.channel().closeFuture().sync();
            log.info("[HelloNettyServer] Netty服务端已启动");
        } catch (Exception e) {
            log.info("[HelloNettyServer] netty服务端启动异常");
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }

}
